package org.vaadin.example.biz.impl;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.vaadin.example.biz.SamplePersonService;
import org.vaadin.example.model.SamplePerson;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class SamplePersonServiceImpl implements SamplePersonService {
    @Override
    public Optional<SamplePerson> get(Long id) {
        return Optional.empty();
    }

    @Override
    public SamplePerson update(SamplePerson entity) {
        return null;
    }

    @Override
    public void delete(Long id) {

    }

    @Override
    public int count() {
        return 0;
    }

    @Override
    public Page<SamplePerson> list(Pageable pageable) {

        List<SamplePerson> samplePersons = new ArrayList<>();

        for (int i = 1; i < 101; i++) {
            samplePersons.add(SamplePerson.builder()
                    .dateOfBirth(LocalDate.now())
                    .email("qwe12e12@126.com")
                    .firstName("Eula"+i)
                    .important(true)
                    .phone("123123123")
                    .lastName("Lane")
                    .occupation("Insurance Clerk")
                    .role("Worker")
                    .id((long) i)
                    .build());
        }
        return convertToPage(samplePersons,pageable);
    }


    public Page<SamplePerson> convertToPage(List<SamplePerson> samplePersonList, Pageable pageable) {
        // 计算总条目数
        long total = samplePersonList.size();

        // 计算当前页的起始和结束索引
        int start = (int) pageable.getOffset();
        int end = Math.min(start + pageable.getPageSize(), (int) total);

        // 获取当前页的数据
        List<SamplePerson> pagedData = samplePersonList.subList(start, end);

        // 创建 PageImpl 对象并返回
        return new PageImpl<>(pagedData, pageable, total);
    }
}
